﻿const cloud = require("wx-server-sdk");
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();

const normalizeString = value => (typeof value === "string" ? value.trim() : "");

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const operatorOpenID = wxContext.OPENID;
  const activityID = normalizeString(event.activityID || event.ActivityID);

  if (!operatorOpenID) {
    return { success: false, error: "未获取到操作用户" };
  }
  if (!activityID) {
    return { success: false, error: "缺少活动编号" };
  }

  try {
    const activityDoc = await db
      .collection("Activity_Information")
      .doc(activityID)
      .get()
      .catch(() => null);

    if (!activityDoc || !activityDoc.data) {
      return { success: false, error: "未找到活动信息" };
    }

    if (activityDoc.data.PublisherOpenID !== operatorOpenID) {
      return { success: false, error: "无权撤销该活动" };
    }

    await db
      .collection("Activity_Information")
      .doc(activityID)
      .update({
        data: {
          Status: "Withdraw",
          WithdrawTime: db.serverDate()
        }
      });

    return { success: true };
  } catch (error) {
    console.error("withdrawActivity error", error);
    return { success: false, error: "撤销失败，请稍后重试" };
  }
};
